package com.fiberhome.nas.feature.main.view

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import com.fiberhome.nas.core.designsystem.theme.AppTheme
import com.fiberhome.nas.core.designsystem.theme.BodyMedium
import com.fiberhome.nas.core.designsystem.theme.Primary
import com.fiberhome.nas.core.designsystem.theme.ShapeMedium
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingLarge
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingSmall
import com.fiberhome.nas.core.model.entity.AlbumInfo
import com.fiberhome.nas.core.model.entity.PhotoItem
import com.fiberhome.nas.core.model.preview.previewDeviceAlbums
import com.fiberhome.nas.core.model.preview.previewPhotos
import com.fiberhome.nas.feature.main.viewmodel.AlbumViewModel

@Composable
fun AlbumSelectRoute(
    viewModel: AlbumViewModel = hiltViewModel(),
    onConfirm: (List<PhotoItem>) -> Unit = {}
) {
    val albums = previewDeviceAlbums
    val photos = previewPhotos

    AlbumSelectScreen(
        albums = albums,
        photos = photos,
        onConfirm = onConfirm
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlbumSelectScreen(
    albums: List<AlbumInfo>,
    photos: List<PhotoItem>,
    onConfirm: (List<PhotoItem>) -> Unit = {}
) {
    val selectedPhotos = remember { mutableStateListOf<PhotoItem>() }
    var showOnlyFavorites by remember { mutableStateOf(false) }
    var currentDate by remember { mutableStateOf("") }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("选择照片") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                    titleContentColor = MaterialTheme.colorScheme.onSurface
                ),
                actions = {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text("仅显示未备份的照片", style = BodyMedium)
                        Switch(
                            checked = showOnlyFavorites,
                            onCheckedChange = { showOnlyFavorites = it }
                        )
                    }
                }
            )
        },
        bottomBar = {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(16.dp)
            ) {
                Button(
                    onClick = { onConfirm(selectedPhotos) },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = selectedPhotos.isNotEmpty()
                ) {
                    Text("上传 (${selectedPhotos.size})")
                }
            }
        }
    ) { paddingValues ->
        val filteredPhotos = if (showOnlyFavorites) {
            photos.filter { !it.isBackedUp }
        } else {
            photos
        }

        // 按日期分组
        val groupedPhotos = filteredPhotos.groupBy { it.date }

        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues),
            horizontalArrangement = Arrangement.spacedBy(SpacePaddingSmall),
            verticalArrangement = Arrangement.spacedBy(SpacePaddingSmall),
            contentPadding = PaddingValues(
                SpacePaddingLarge,
                SpacePaddingLarge,
                SpacePaddingLarge,
                SpacePaddingLarge
            ),
        ) {
            groupedPhotos.forEach { (date, photosInDate) ->
//                item(span = { GridCells.Fixed(2).getSpanSize(0, 2) }) {
//                    Text(
//                        text = date,
//                        style = BodyLarge,
//                        modifier = Modifier.padding(vertical = 8.dp)
//                    )
//                }

                items(photosInDate) { photo ->
                    PhotoSelectItem(
                        photo = photo,
                        isSelected = selectedPhotos.contains(photo),
                        onSelectChange = { isSelected ->
                            if (isSelected) {
                                selectedPhotos.add(photo)
                            } else {
                                selectedPhotos.remove(photo)
                            }
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun PhotoSelectItem(
    modifier: Modifier = Modifier,
    photo: PhotoItem,
    isSelected: Boolean,
    onSelectChange: (Boolean) -> Unit
) {
    Box(
        modifier = modifier
            .aspectRatio(1f)
            .clip(ShapeMedium)
            .clickable { onSelectChange(!isSelected) }
    ) {
        // 照片内容
        AsyncImage(
            model = photo.imageResId,
            contentDescription = "照片",
            modifier = Modifier.fillMaxSize()
        )

        // 选中状态指示器
        Box(
            modifier = Modifier
                .padding(8.dp)
                .size(24.dp)
                .align(Alignment.TopEnd)
                .background(
                    color = if (isSelected) Primary else Color.White.copy(alpha = 0.7f),
                    shape = ShapeMedium
                )
                .border(
                    width = 1.dp,
                    color = if (isSelected) Primary else Color.Gray,
                    shape = ShapeMedium
                ),
            contentAlignment = Alignment.Center
        ) {
            if (isSelected) {
                Icon(
                    painter = painterResource(id = android.R.drawable.checkbox_on_background),
                    contentDescription = "已选择",
                    tint = Color.White,
                    modifier = Modifier.size(16.dp)
                )
            }
        }

        // 未备份标记
        if (!photo.isBackedUp) {
            Box(
                modifier = Modifier
                    .padding(8.dp)
                    .size(12.dp)
                    .align(Alignment.BottomEnd)
                    .background(Color.Blue, ShapeMedium)
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun AlbumSelectScreenPreview() {
    AppTheme {
        AlbumSelectScreen(
            albums = previewDeviceAlbums,
            photos = previewPhotos
        )
    }
}